class SyncStatusManager {
  constructor() {
    this.currentSync = null;
    this.syncHistory = [];
  }

  // 开始同步
  startSync(type, packageNames = []) {
    this.currentSync = {
      id: `sync-${Date.now()}`,
      type,
      packageNames,
      status: 'running',
      startTime: new Date(),
      progress: 0,
      totalPackages: packageNames.length || 25, // 默认热门包数量
      processedPackages: 0,
      successCount: 0,
      failureCount: 0,
      currentPackage: null,
      errors: []
    };
    
    console.log('同步任务开始:', this.currentSync.id);
    return this.currentSync.id;
  }

  // 更新同步进度
  updateProgress(packageName, success = true, error = null) {
    if (!this.currentSync) return;

    this.currentSync.processedPackages++;
    this.currentSync.currentPackage = packageName;
    this.currentSync.progress = Math.round((this.currentSync.processedPackages / this.currentSync.totalPackages) * 100);

    if (success) {
      this.currentSync.successCount++;
    } else {
      this.currentSync.failureCount++;
      if (error) {
        this.currentSync.errors.push({
          package: packageName,
          error: error.message || error
        });
      }
    }

    console.log(`同步进度: ${this.currentSync.progress}% (${this.currentSync.processedPackages}/${this.currentSync.totalPackages}) - 当前: ${packageName}`);
  }

  // 完成同步
  completeSync(success = true) {
    if (!this.currentSync) return;

    this.currentSync.status = success ? 'completed' : 'failed';
    this.currentSync.endTime = new Date();
    this.currentSync.duration = Math.round((this.currentSync.endTime - this.currentSync.startTime) / 1000);
    this.currentSync.progress = 100;

    // 添加到历史记录
    this.syncHistory.unshift({
      ...this.currentSync
    });

    // 只保留最近50条记录
    if (this.syncHistory.length > 50) {
      this.syncHistory = this.syncHistory.slice(0, 50);
    }

    console.log('同步任务完成:', this.currentSync.id, '状态:', this.currentSync.status);
    this.currentSync = null;
  }

  // 取消同步
  cancelSync() {
    if (!this.currentSync) return false;

    this.currentSync.status = 'cancelled';
    this.currentSync.endTime = new Date();
    this.currentSync.duration = Math.round((this.currentSync.endTime - this.currentSync.startTime) / 1000);

    // 添加到历史记录
    this.syncHistory.unshift({
      ...this.currentSync
    });

    console.log('同步任务已取消:', this.currentSync.id);
    this.currentSync = null;
    return true;
  }

  // 获取当前同步状态
  getCurrentStatus() {
    if (!this.currentSync) {
      return {
        isSyncing: false,
        progress: 0,
        statusText: '空闲',
        lastSyncTime: this.syncHistory.length > 0 ? this.syncHistory[0].endTime : null,
        progressText: '准备就绪'
      };
    }

    return {
      isSyncing: true,
      progress: this.currentSync.progress,
      statusText: '同步中',
      lastSyncTime: this.currentSync.startTime,
      progressText: `正在处理: ${this.currentSync.currentPackage || '准备中'} (${this.currentSync.processedPackages}/${this.currentSync.totalPackages})`,
      currentSync: this.currentSync
    };
  }

  // 获取同步历史
  getHistory(limit = 10) {
    return {
      items: this.syncHistory.slice(0, limit).map(sync => ({
        id: sync.id,
        type: sync.type === 'trending' ? 'full' : 'custom',
        status: sync.status,
        packagesSynced: sync.processedPackages,
        packagesSuccess: sync.successCount,
        packagesFailed: sync.failureCount,
        duration: sync.duration,
        startedAt: sync.startTime?.toLocaleString('zh-CN'),
        completedAt: sync.endTime?.toLocaleString('zh-CN')
      })),
      total: this.syncHistory.length
    };
  }

  // 获取同步详情
  getHistoryDetail(id) {
    const sync = this.syncHistory.find(s => s.id === id);
    if (!sync) return null;

    return {
      id: sync.id,
      type: sync.type === 'trending' ? 'full' : 'custom',
      status: sync.status,
      sourceUrl: 'https://registry.npmjs.org/',
      packagesSynced: sync.processedPackages,
      packagesSuccess: sync.successCount,
      packagesFailed: sync.failureCount,
      duration: sync.duration,
      startedAt: sync.startTime?.toLocaleString('zh-CN'),
      completedAt: sync.endTime?.toLocaleString('zh-CN'),
      errorMessage: sync.errors.length > 0 ? `${sync.errors.length} 个包同步失败` : null,
      failedPackages: sync.errors.map(err => ({
        name: err.package,
        error: err.error
      }))
    };
  }

  // 清空历史记录
  clearHistory() {
    this.syncHistory = [];
  }
}

// 创建单例实例
const syncStatusManager = new SyncStatusManager();

module.exports = syncStatusManager;